package com.athuahua.spzx.service.impl;

import com.athuahua.spzx.dto.h5.UserLoginDto;
import com.athuahua.spzx.dto.h5.UserRegisterDto;
import com.athuahua.spzx.entity.UserCollect;
import com.athuahua.spzx.exception.CodeException;
import com.athuahua.spzx.mapper.UserCollectMapper;
import com.athuahua.spzx.properties.JwtProperties;
import com.athuahua.spzx.utils.BaseContext;
import com.athuahua.spzx.utils.JwtUtil;
import com.athuahua.spzx.utils.ResultCodeEnum;
import com.athuahua.spzx.vo.h5.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.UserInfo;
import com.athuahua.spzx.service.UserInfoService;
import com.athuahua.spzx.mapper.UserInfoMapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author huahua
 * @description 针对表【user_info(会员表)】的数据库操作Service实现
 * @createDate 2024-08-13 16:04:25
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserCollectMapper userCollectMapper;

    @Override
    @Transactional
    public void register(UserRegisterDto userRegisterDto) {
        //校验码验证
        String code = redisTemplate.opsForValue().get(userRegisterDto.getUsername());
        if (code == null || !code.equals(userRegisterDto.getCode())) {
            throw new CodeException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //判断用户名是否存在
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUsername, userRegisterDto.getUsername())
        );
        if (userInfo != null) {
            throw new CodeException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //保存用户信息
        UserInfo user = new UserInfo();
        user.setUsername(userRegisterDto.getUsername());
        user.setPassword(DigestUtils.md5DigestAsHex(userRegisterDto.getPassword().getBytes()));
        user.setPhone(userRegisterDto.getUsername());
        user.setStatus(1);
        user.setSex(0);
        user.setNickName(userRegisterDto.getNickName());
        user.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");

        userInfoMapper.insert(user);
       // userInfoMapper.insertTestAddress(user);

        //5.从redis删除验证码信息
        redisTemplate.delete(userRegisterDto.getUsername());
    }

    @Override
    public String login(UserLoginDto userLoginDto) {
        if (userLoginDto.getPassword() == null || userLoginDto.getUsername() == null) {
            throw new CodeException(ResultCodeEnum.LOGIN_ERROR);
        }
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUsername, userLoginDto.getUsername())
        );
        if (userInfo == null) {
            throw new CodeException(ResultCodeEnum.DOESNOTUSER_ERROR);
        }
        if (!userInfo.getPassword().equals(DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes()))) {
            throw new CodeException(ResultCodeEnum.LOGIN_ERROR);
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName",  userInfo.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(), //key
                jwtProperties.getUserTtl(), //过期时间
                claims);

        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo() {
        //1、从请求头中获取令牌
        Long currentId = BaseContext.getCurrentId();
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getId, currentId));
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setNickName(userInfo.getNickName());
        userInfoVo.setAvatar(userInfo.getAvatar());


        return userInfoVo;
    }

    @Override
    public boolean isCollect(Long skuId) {
        UserCollect userCollect = userCollectMapper.selectOne(new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, BaseContext.getCurrentId())
                .eq(UserCollect::getSkuId, skuId));
        return userCollect != null;
    }

    @Override
    public void collect(Long skuId) {
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(BaseContext.getCurrentId());
        userCollect.setSkuId(skuId);
        userCollectMapper.insert(userCollect);
    }

    @Override
    public void cancelCollect(Long skuId) {
        userCollectMapper.delete(new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, BaseContext.getCurrentId())
                .eq(UserCollect::getSkuId, skuId));
    }
}




